<?php
/*
 * @Author: CHINAKAIYUAN<sunkaiyuan@namenode.cn>
 * @Date: 2022-02-03 01:21:39
 * @LastEditTime: 2023-07-21 14:26:59
 * @LastEditors: 孙开源 && sunkaiyuan@namenode.cn
 * @Description: 
 */

namespace App\Traits;

use App\Models\Attachment;
use Illuminate\Support\Facades\Storage;

trait AttachmentTrait
    {

    private $_attachmentkey = 'code';

    public function AttachmentTraitDeleting()
        {
        $this->attachments->filter(function ($attachment)
            {
            $attachment->update(['source_deleted' => 1]);
            });
        }
    public function attachments()
        {
        $key = $this->getAttachmentkey();
        return $this->hasMany(Attachment::class, "source_value", $key)->where(function ($query) use ($key)
            {
            $query->where("source_key", $key)
                ->where("source_model", $this::class);
            });
        }
    public function firstAttachment()
        {
        $key = $this->getAttachmentkey();
        return $this->hasOne(Attachment::class, "source_value", $key)->where(function ($query) use ($key)
            {
            $query->where("source_key", $key)
                ->where("source_model", $this::class);
            });
        }
    public function getAttachmentkey()
        {
        $key = $this->_attachmentkey;
        if (property_exists(__CLASS__, "attachmentkey"))
            $key = $this->attachmentkey;
        return $key;
        }
    }